package gov.child.web.controller;

import gov.child.entities.vo.Department;
import gov.child.entities.vo.Guide;
import gov.child.entities.vo.Page;
import gov.child.service.DepartmentService;
import gov.child.service.GuideService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author fzh
 * @since 2017/9/11
 */
@Controller
@RequestMapping("/enterprise")
public class EnterpriseWorkController {
    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private GuideService guideService;

    @GetMapping
    public ModelAndView index(HttpSession session) {
        List departments = initDept(session);
        Page page = guideService.getPage(10);
        List result = guideService.findAll(page);
        ModelAndView mv = new ModelAndView("enterpriseWork");
        mv.addObject("guides", result);
        mv.addObject("page", page);
        return mv;
    }

    @GetMapping("/select")
    public ModelAndView res(@RequestParam Integer id, @RequestParam(required = false) Boolean online) {
        List r;
        Department department = new Department();
        department.setDepartmentId(id);
        if (online != null && online) {
            r = guideService.find(department, true, Guide.ENTERPRISE, Guide.PERSONAL_ENTERPRISE);
        } else {
            r = guideService.find(department, false, Guide.ENTERPRISE, Guide.PERSONAL_ENTERPRISE);
        }
        ModelAndView mv = new ModelAndView("enterpriseWork");
        mv.addObject("guides", r);
        mv.addObject("online", online != null);
        return mv;
    }

    private List initDept(HttpSession session) {
        List departments;
        Object o = session.getAttribute("depts");
        if (o == null) {
            departments = departmentService.findParentDepartment();
            session.setAttribute("depts", departments);
        } else {
            departments = (List) o;
        }
        return departments;
    }
}
